<template>
  <div class="mod-config">
    <el-form :inline="true" ref="dataForm" :model="dataForm" @keyup.enter.native="query()">
      <el-form-item>
        <el-popover ref="dtListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="dtList"
            :props="dtListTreeProps"
            node-key="id"
            ref="dtTree"
            @current-change="dtListTreeCurrentChange"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
            style="width:194px"
          ></el-tree>
        </el-popover>
        <el-input
          v-model="dataForm.dtName"
          v-popover:dtListPopover
          :readonly="true"
          placeholder="点击选择所属机构"
          style="width:194px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.province" clearable @change="proChange" placeholder="请选择省份">
          <el-option
            v-for="item in provinces"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.city" clearable @change="cityChange" placeholder="请选择城市">
          <el-option
            v-for="item in citys"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.county" clearable placeholder="请选择区域">
          <el-option
            v-for="item in countys"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="dataForm.blonPlantform"
          clearable
          @change="pfChange"
          placeholder="请选择销售平台"
        >
          <el-option v-for="item in pfs" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="store">
        <el-select v-model="dataForm.store" clearable @change="storeChange" placeholder="请选择店铺">
          <el-option v-for="item in stores" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
        <el-select v-model="dataForm.brand" clearable placeholder="请选择品牌">
          <el-option
            v-for="item in brands"
            :key="item.bcode"
            :label="item.bname"
            :value="item.bcode"
          ></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item>
        <el-select v-model="dataForm.group" clearable placeholder="请选择分组">
          <el-option v-for="item in groups" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status" clearable placeholder="请选择状态">
          <el-option v-for="item in statuss" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.name" clearable placeholder="酒店名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="query()">查询</el-button>
        <el-button type="primary" @click="select" :disabled="dataListSelections.length <= 0">添加</el-button>
        <el-button v-if="isAuth('op:hotel:send')" type="primary" @click="sendHotel">推送</el-button>
        <el-button v-if="isAuth('op:hotel:alidel')" type="danger" @click="aliDel">删除(飞猪)</el-button>
        <el-button v-if="isAuth('op:hotel:up')" type="primary" @click="upHotel">上架</el-button>
        <el-button v-if="isAuth('op:hotel:down')" type="danger" @click="downHotel">下架</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="hotelinfo-table-expand">
            <el-form-item label="酒店编码">
              <span>{{ props.row.hotelId }}</span>
            </el-form-item>
            <el-form-item label="坐标类型">
              <el-tag v-if="props.row.axes === 'G'" size="small" type="info">谷歌</el-tag>
              <el-tag v-else-if="props.row.axes === 'B'" size="small" type="info">百度</el-tag>
              <el-tag v-else-if="props.row.axes === 'A'" size="small" type="info">高德</el-tag>
              <el-tag v-else-if="props.row.axes === 'M'" size="small" type="info">灵图</el-tag>
            </el-form-item>
            <el-form-item label="经度">
              <span>{{ props.row.axesX }}</span>
            </el-form-item>
            <el-form-item label="纬度">
              <span>{{ props.row.axesY }}</span>
            </el-form-item>
            <el-form-item label="星级">
              <el-tag v-if="props.row.starLevel === '3'" size="small" type="info">3星以下</el-tag>
              <el-tag v-else-if="props.row.starLevel === '4'" size="small" type="info">4星</el-tag>
              <el-tag v-else-if="props.row.starLevel === '5'" size="small" type="info">5星</el-tag>
              <el-tag v-else-if="props.row.starLevel === '6'" size="small" type="info">5星以上</el-tag>
            </el-form-item>
            <el-form-item label="酒店地址">
              <span>{{ props.row.address }}</span>
            </el-form-item>
            <el-form-item label="联系电话">
              <span>{{ props.row.phone }}</span>
            </el-form-item>
            <el-form-item label="品牌">
              <span>{{ props.row.brandName }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="dtName" header-align="center" align="center" label="分销商"></el-table-column>
      <el-table-column prop="storName" header-align="center" align="center" label="店铺"></el-table-column>
      <el-table-column prop="hotelName" header-align="center" align="center" label="酒店"></el-table-column>
      <el-table-column prop="status" header-align="left" align="left" label="上架状态" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === -1" size="small" type="success">未推送</el-tag>
          <el-tag v-else-if="scope.row.status === 0" size="small" type="success">在售</el-tag>
          <el-tag v-else-if="scope.row.status === -2" size="small" type="success">停售</el-tag>
          <el-tag v-else size="small" type="warning">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="180" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            v-if="isAuth('ht:hthotelinfo:addprice')"
            @click="addPrice(scope.row)"
          >加价</el-button>
          <el-button
            type="text"
            v-if="isAuth('op:hotel:down') && scope.row.status === -1"
            size="small"
            @click="deleteHandle(scope.row.id)"
          >删除</el-button>
          <el-button type="text" @click="viewHotel(scope.row.hotelName)">详情</el-button>
          <el-button type="text" v-if="scope.row.isAuto !== 1" @click="setAutoOrder(scope.row.id,1)" >自动下单</el-button>
          <el-button type="text" v-if="scope.row.isAuto === 1" @click="setAutoOrder(scope.row.id,0)" >手动下单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import { treeDataTranslate } from '@/utils'
import AddOrUpdate from './dtuphtl-add-or-update'
export default {
  data() {
    return {
      hotelUpDownHtlDto: {
        storeId: null,
        status: 0,
        hotelList: []
      },
      dataForm: {
        province: null,
        city: null,
        county: null,
        dtId: null,
        brand: null,
        group: null,
        status: null,
        dtName: '',
        blonPlantform: null,
        store: null,
        hotelName: '',
        hotels: []
      },
      dtList: [],
      dtListTreeProps: {
        label: 'name',
        children: 'children'
      },
      tier: 1,
      parentId: -1,
      provinces: [],
      citys: [],
      countys: [],
      brands: [],
      groups:[],
      statuss: [{ id: -1, name: '未推送' }, { id: 0, name: '在售' }, { id: -2, name: '停售' }],
      pfs: [],
      stores: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      dataRule: {
        store: [
          { required: true, message: '请选择店铺', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDtPf()
    this.getQuryCitys()
    this.getBrands()
  },
  methods: {
    // 获取机构及销售平台下拉列表数据
    getDtPf() {
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/dtpf'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.pfs = data.spfs
          if (data.dts.length > 0) {
            this.dataForm.dtId = data.dts[0].id
          }
          this.dtList = treeDataTranslate(data.dts, 'id')
          this.$nextTick(function () {
            this.dtListTreeSetCurrentNode()
          })
        }
      })
    },
    // 获取区域查询条件
    getQuryCitys() {
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/citys'),
        method: 'post',
        params: this.$http.adornParams({
          tier: this.tier,
          parentId: this.parentId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          switch (this.tier) {
            case 1:
              this.provinces = data.list
              break
            case 2:
              this.citys = data.list
              break
            case 3:
              this.countys = data.list
              break
          }
        }
      })
    },
    // 加价
    addPrice(data) {
      this.$router.push({ name: 'op-htlprice', params: { hotel: data, storeId: this.dataForm.store} })
    },
    // 选择省份
    proChange(value) {
      this.parentId = value
      this.tier = 2
      this.getQuryCitys()
    },
    // 选择城市
    cityChange(value) {
      this.parentId = value
      this.tier = 3
      this.getQuryCitys()
    },
    // 查询店铺信息
    getStore() {
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/store'),
        method: 'get',
        params: this.$http.adornParams({
          "dtId": this.dataForm.dtId,
          "pfId": this.dataForm.blonPlantform
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.stores = data.list
        }
      })
    },
    // 查询品牌
    getBrands() {
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/brand'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.brands = data.list
        }
      })
    },
    //查询分组
    getGroups() {
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/group'),
        method: 'get',
        params: this.$http.adornParams({
          "dtId": this.dataForm.dtId,
          "pf": this.dataForm.blonPlantform,
          "storId": this.dataForm.store
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.groups = data.list
        }
      })
    },
    // 分销商树选中
    dtListTreeCurrentChange(data, node) {
      this.dataForm.dtId = data.id
      this.dataForm.dtName = data.name
      this.$nextTick(function () {
        this.getStore()
      })
    },
    // 分销商设置当前选中节点
    dtListTreeSetCurrentNode() {
      if (this.dataForm.dtId != null) {
        this.$refs.dtTree.setCurrentKey(this.dataForm.dtId)
        this.dataForm.dtName = (this.$refs.dtTree.getCurrentNode() || {})['name']
      }
    },
    // 选择销售平台
    pfChange(value) {
      this.getStore()
    },
    // 选择店铺
    storeChange(value) {
      this.getGroups()
    },
    query() {
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取数据列表
    getDataList() {
      // 必须选择店铺
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        console.log("valid", valid)
      })
      if (this.dataForm.store === null || this.dataForm.store === '') {
        this.$alert('请选择店铺', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/op/dtuphtl/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          // 'province': this.dataForm.province,
          'city': this.dataForm.city,
          'county': this.dataForm.county,
          'dtId': this.dataForm.dtId,
          'pfId': this.dataForm.blonPlantform,
          'storId': this.dataForm.store,
          'group': this.dataForm.group,
          'brand': this.dataForm.brand,
          'status': this.dataForm.status,
          'name': this.dataForm.name
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(this.dataForm.dtId, this.pfs, this.provinces, this.brands)
      })
    },
    select() {
      if (this.dataListSelections.length <= 0) {
        return
      }

      let ids = this.dataListSelections.map(item => {
        return { hotelId: item.hotelId, status: item.status }
      })
      // 把选择的酒店添加到酒店列表
      this.hotelUpDownHtlDto.hotelList = this.hotelUpDownHtlDto.hotelList.concat(ids)
      // 去重
      let obj = {}
      this.hotelUpDownHtlDto.hotelList = this.hotelUpDownHtlDto.hotelList.reduce((cur, next) => {
        obj[next.hotelId] ? "" : obj[next.hotelId] = true && cur.push(next)
        return cur
      }, [])
      this.dataListSelections = []
    },

    //推送
    sendHotel() {
      this.select()
      this.hotelUpDownHtlDto.storeId = this.dataForm.store
      this.hotelUpDownHtlDto.hotelList = this.hotelUpDownHtlDto.hotelList.map(item => {
        return item.hotelId
      })
      if (this.hotelUpDownHtlDto.hotelList.length <= 0) {
        this.$alert('请选择并添加酒店', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.$confirm(`确定推送[${this.hotelUpDownHtlDto.hotelList.length}]家酒店吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/op/dtuphtl/ali/send'),
          method: 'post',
          data: this.$http.adornData(this.hotelUpDownHtlDto, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
              }
            })
          } else {
            this.$message.error(data.msg)
          }
          this.hotelUpDownHtlDto.hotelList = []
        })
      })
    },
    //删除飞猪店铺上的酒店
    aliDel() {
      this.select()
      this.hotelUpDownHtlDto.storeId = this.dataForm.store
      this.hotelUpDownHtlDto.status = -1
      if (this.hotelUpDownHtlDto.hotelList.length <= 0) {
        this.$alert('请选择并添加酒店', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.$confirm(`确定删除[${this.hotelUpDownHtlDto.hotelList.length}]家酒店吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/op/dtuphtl/ali/del'),
          method: 'post',
          data: this.$http.adornData(this.hotelUpDownHtlDto, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
              }
            })
          } else {
            this.$message.error(data.msg)
          }
          this.hotelUpDownHtlDto.hotelList = []
        })
      })
    },
    // 上架
    upHotel() {
      this.select()
      this.hotelUpDownHtlDto.storeId = this.dataForm.store
      this.hotelUpDownHtlDto.status = 0
      console.log("this.hotelUpDownHtlDto", this.hotelUpDownHtlDto)
      if (this.hotelUpDownHtlDto.hotelList.length <= 0) {
        this.$alert('请选择并添加酒店', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.$confirm(`确定上架[${this.hotelUpDownHtlDto.hotelList.length}]家酒店吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/op/dtuphtl/ali/up'),
          method: 'post',
          data: this.$http.adornData(this.hotelUpDownHtlDto, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
              }
            })
          } else {
            this.$message.error(data.msg)
          }
          this.hotelUpDownHtlDto.hotelList = []
        })
      })
    },
    // 下架
    downHotel() {
      this.select()
      this.hotelUpDownHtlDto.storeId = this.dataForm.store
      this.hotelUpDownHtlDto.status = -2
      console.log("this.hotelUpDownHtlDto", this.hotelUpDownHtlDto)
      if (this.hotelUpDownHtlDto.hotelList.length <= 0) {
        this.$alert('请选择并添加酒店', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.$confirm(`确定下架[${this.hotelUpDownHtlDto.hotelList.length}]家酒店吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/op/dtuphtl/ali/down'),
          method: 'post',
          data: this.$http.adornData(this.hotelUpDownHtlDto, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
              }
            })
          } else {
            this.$message.error(data.msg)
          }
          this.hotelUpDownHtlDto.hotelList = []
        })
      })
    },
    // 删除
    deleteHandle(id) {
      this.$confirm(`确定对[id=${id}]进行}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/op/dtuphtl/delete'),
          method: 'post',
          data: this.$http.adornData([id], false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    viewHotel(hotelName) {
      this.$router.push({ name: 'ht-hthotelinfo', params: { hotelName: hotelName } })
    },
    //设置自动下单
    setAutoOrder(id,isAuto){
       this.$confirm(`确定对[id=${id}]设置${isAuto===1?"设置":"取消"}自动下单吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/op/dtuphtl/auto/order/${id}/${isAuto}`),
          method: "get",
          params: this.$http.adornParams(),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
}
</script>
<style>
.hotelinfo-table-expand {
  font-size: 0;
}
.hotelinfo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.hotelinfo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
